<template>
    <el-dialog
      v-model="visible"
      title="编辑用户信息"
      width="600px"
      @closed="resetForm"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" disabled />
        </el-form-item>
  
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" />
        </el-form-item>
  
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
  
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
  
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex">
            <el-option :value="0" label="男" />
            <el-option :value="1" label="女" />
            <el-option :value="2" label="未知" />
          </el-select>
        </el-form-item>
  
        <el-form-item label="生日">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>
  
        <el-form-item label="个人简介">
          <el-input
            v-model="form.introduction"
            type="textarea"
            :rows="3"
            placeholder="请输入用户简介"
          />
        </el-form-item>
      </el-form>
  
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, reactive, watch, 
   // nextTick
 } from 'vue'
  import { ElMessage } from 'element-plus'
  import { updateUser } from '@/api/user'
  import dayjs from 'dayjs'
  
  const props = defineProps({
    userData: {
      type: Object,
      required: true,
      default: () => ({
        id: '',
        userName: '',
        nickName: '',
        email: '',
        phone: '',
        sex: 0,
        birthday: '',
        introduction: ''
      })
    }
  })
  const rules = reactive({
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
})

  
  const emit = defineEmits(['success'])
  
  const visible = ref(false)
  const formRef = ref(null)
  const form = reactive({
    id: '',
    userName: '',
    nickName: '',
    email: '',
    phone: '',
    sex: 0,
    birthday: '',
    introduction: ''
  })
  
  // 核心修复：使用 watch 深度监听 + nextTick 确保数据同步
  watch(() => props.userData, (newVal) => {
    Object.assign(form, {
      ...newVal,
      // 转换日期格式（假设后端返回的是时间戳或ISO字符串）
      birthday: newVal.birthday ? dayjs(newVal.birthday).format('YYYY-MM-DD') : ''
    })
  }, { deep: true, immediate: true })
  
//   // 优化打开方法
//   const open = async () => {
//     await nextTick() // 等待DOM更新
//     visible.value = true
//   }
  const open = () => {
  // 确保使用最新 props 数据
  Object.assign(form, {
    ...props.userData,
    birthday: dayjs(props.userData.birthday).format('YYYY-MM-DD')
  })
  visible.value = true
}
  
  
  // 提交时转换日期格式
  const submitForm = async () => {
    try {
      await formRef.value.validate()
      const payload = {
        ...form,
        birthday: form.birthday ? dayjs(form.birthday).format('YYYY-MM-DD HH:mm:ss') : null
      }
      const { code } = await updateUser(payload)
      if (code === 200) {
        ElMessage.success('修改成功')
        visible.value = false
        emit('success')
      }
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('修改失败: ' + error.message)
    }
  }
  
  // 重置表单时恢复默认值
  const resetForm = () => {
    Object.assign(form, {
      ...props.userData,
      birthday: props.userData.birthday ? dayjs(props.userData.birthday).format('YYYY-MM-DD') : ''
    })
  }
  
  defineExpose({ open })
  </script>